//
//  CHOAuthController.swift
//  status
//
//  Created by 彳亍 on 2017/3/22.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit
import SVProgressHUD

class CHOAuthController: UIViewController {
    
    /// web 视图
    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        super.loadView()
        view = webView
        webView.delegate = self
        webView.scrollView.isScrollEnabled = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "OAuth授权"
        view.backgroundColor = UIColor.white
        
        let  image = UIImage(named:"navigationbar_back_highlighted")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: image,
                                                           style: .plain,
                                                           target: self,
                                                           action: #selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(tilte: "自动填充", target: self, action: #selector(autoFill)
        )
        
        // 加载网页
        loadWebView()
    }
    
    /// 关闭控制器
    @objc func close() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    /// 加载视图
    private func loadWebView() {
        /// 授权链接
        let loadUrlString = "\(CHOAuth2AuthorizeUrl)?client_id=\(CHClientId)&redirect_uri=\(CHRedirectUri)"
        
        guard let loadUrl = URL(string:loadUrlString) else { return }
        
        webView.loadRequest(URLRequest(url: loadUrl))
    }
    
    /// 自动填充
    @objc private func autoFill() {
        // 准备 js
        let javaScript = "document.getElementById(\"userId\").value = \"18612651688\";" +
        "document.getElementById(\"passwd\").value = \"4110215217\";"
        // 注入 js
        webView.stringByEvaluatingJavaScript(from: javaScript)
    }
    
}

// MARK: - UIWebViewDelegate
extension CHOAuthController:UIWebViewDelegate {
    
    /// shouldStartLoadWith
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 加载非回调页
        if request.url?.absoluteString.hasPrefix(CHRedirectUri) == false {
            return true
        }
        
        // 用户取消授权
        if request.url?.query?.hasPrefix("code=") == false {
            
            close()
            
            return false
        }
        
        // 用户授权 / 获取code
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        //FIXME: 请求 访问令牌
        CHHTTPSessionManager.shared.loadAccessToken(code: code) { (isSuccess) in
            // 授权失败
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "授权失败")
            }else {
                // 发送登录成功通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: CHUserLoginSuccessNotification),
                                                object: nil)
            }
            
            // 关闭窗口
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                self.close()
            })
            
        }
        
        return false
    }
    
    /// webViewDidStartLoad
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    /// webViewDidFinishLoad
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// didFailLoadWithError
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        print(error)
    }
    
}
